package com.book_management.service.impl;

import com.book_management.dao.SysUserDao;
import com.book_management.dao.SysUserRoleDao;
import com.book_management.entity.SysRole;
import com.book_management.entity.SysUser;
import com.book_management.entity.SysUserRole;
import com.book_management.exception.ExceptionCatch;
import com.book_management.service.SysUserService;
import com.book_management.util.IdWorkerUtil;
import com.book_management.util.Sha256Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;

/**
 * @author xiangqian
 * @date 2022/12/3 11:45
 * @description:
 */

@Service
public class SysUserServiceImpl implements SysUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private IdWorkerUtil idWorkerUtil;

    /**
     * 新增用户
     * @param sysUser
     */
    @Override
    public void insertSysUser(SysUser sysUser) {

        //注册判空时，只需要判断手机号是否存在即可，不需要其他判断
        Optional<SysUser> userInfo = Optional.ofNullable(sysUserDao.selectUserByPhone(sysUser.getPhone()));
        if (sysUser.getPhone().isEmpty() || sysUser.getPassword().isEmpty()){
            LOGGER.error("账号或密码为空，请重启输入！");
        }
        if (userInfo.isPresent()){
            LOGGER.error("注册失败，当前账号已存在！");
        }
        // new time 进行调用
        LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        sysUser.setId(idWorkerUtil.nextId());
        sysUser.setCreateTime(date);
        sysUser.setFinalTime(date);
        sysUser.setPassword(Sha256Util.getSHA256(sysUser.getPassword()));
        sysUserDao.insert(sysUser);

        SysUserRole sysUserRole = SysUserRole.builder()
                .roleId(2)
                .userId(sysUser.getId())
                .build();
        sysUserRoleDao.insert(sysUserRole);

    }


    /**
     * 查询用户登录
     * @param sysUser
     * @return
     */
    @Override
    public String selectUserBySysUserInfo(SysUser sysUser) {
        return null;
    }

}
